<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import {
  login,
  getUserInfo,
  logout,
  getUserList,
  type UserInfo,
  type LoginParams,
} from "@/api/user";

// 响应式数据
const userInfo = ref<UserInfo | null>(null);
const userList = ref<UserInfo[]>([]);
const loading = ref(false);
const loginFormRef = ref<FormInstance>();

// 登录表单
const loginForm = reactive<LoginParams>({
  username: "",
  password: "",
});

// 表单验证规则
const loginRules: FormRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
};

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const result = await login(loginForm);
        localStorage.setItem("token", result.data.token);
        userInfo.value = result.data.userInfo;
        ElMessage.success("登录成功！");
        resetForm();
      } catch (error) {
        console.error("登录失败：", error);
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.resetFields();
};

// 退出登录
const handleLogout = async () => {
  try {
    await logout();
    localStorage.removeItem("token");
    userInfo.value = null;
    ElMessage.success("退出成功！");
  } catch (error) {
    console.error("退出失败：", error);
  }
};

// 加载用户列表
const loadUserList = async () => {
  try {
    const result = await getUserList();
    userList.value = result.data.list;
  } catch (error) {
    console.error("获取用户列表失败：", error);
  }
};

// 检查登录状态
const checkLoginStatus = async () => {
  const token = localStorage.getItem("token");
  if (token) {
    try {
      const result = await getUserInfo();
      userInfo.value = result.data;
    } catch (error) {
      console.error("获取用户信息失败：", error);
      localStorage.removeItem("token");
    }
  }
};

// 组件挂载时执行
onMounted(() => {
  checkLoginStatus();
  loadUserList();
});
</script>

<template>
  <div class="home">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>Vue3 + TypeScript + Element Plus 示例</span>
        </div>
      </template>

      <el-space direction="vertical" size="large" style="width: 100%">
        <!-- 用户信息 -->
        <el-card v-if="userInfo" shadow="never">
          <template #header>
            <el-icon><User /></el-icon>
            <span style="margin-left: 8px">用户信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
            <el-descriptions-item label="角色">{{
              userInfo.roles.join(", ")
            }}</el-descriptions-item>
            <el-descriptions-item label="头像">
              <el-avatar :src="userInfo.avatar" :size="40" />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 登录表单 -->
        <el-card v-else shadow="never">
          <template #header>
            <el-icon><Lock /></el-icon>
            <span style="margin-left: 8px">用户登录</span>
          </template>
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入用户名（admin/user）" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码（123456）"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogin" :loading="loading"> 登录 </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 用户列表 -->
        <el-card shadow="never">
          <template #header>
            <el-icon><List /></el-icon>
            <span style="margin-left: 8px">用户列表</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="loadUserList">
              刷新
            </el-button>
          </template>
          <el-table :data="userList" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="roles" label="角色">
              <template #default="scope">
                <el-tag v-for="role in scope.row.roles" :key="role" style="margin-right: 4px">
                  {{ role }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="头像" width="80">
              <template #default="scope">
                <el-avatar :src="scope.row.avatar" :size="40" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 操作按钮 -->
        <el-card v-if="userInfo" shadow="never">
          <el-button type="danger" @click="handleLogout">退出登录</el-button>
        </el-card>
      </el-space>
    </el-card>
  </div>
</template>

<style scoped>
.home {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.box-card {
  max-width: 800px;
  margin: 0 auto;
}
</style>
